/**
 * 
 */
package com.jolestar.yayaweibotong.controller;

import java.io.IOException;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.jolestar.yayaweibotong.ServiceType;
import com.jolestar.yayaweibotong.YaYaAccessToken;
import com.jolestar.yayaweibotong.YaYaRequestToken;
import com.jolestar.yayaweibotong.dao.AccountDomain;
import com.jolestar.yayaweibotong.dao.DomainFactory;
import com.jolestar.yayaweibotong.dao.UserDomain;
import com.jolestar.yayaweibotong.service.UserService;

/**
 * @author jolestar@gmail.com
 * 
 */
public class CallbackAction extends AbstractAction {

	private static final Logger log = Logger.getLogger(CallbackAction.class
			.getName());

	public CallbackAction() {
		super("callback");
	}


	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.jolestar.yayaweibotong.controller.AbstractAction#doAction(javax.servlet
	 * .http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
	 */
	@Override
	protected String doAction(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String type = request.getParameter("service_type");
		ServiceType serviceType = ServiceType.fromName(type);
		if (serviceType == null) {
			return "error:500";
		}
		YaYaRequestToken requestToken = (YaYaRequestToken) request.getSession(
				true).getAttribute("requestToken");
		if (requestToken == null) {
			return "error:500";
		}
		// 这个参旧版本的OAuth 认证没有
		String verifier = request.getParameter("oauth_verifier");

		YaYaAccessToken accessToken = serviceType.getOAuthService()
				.requestAccessToken(requestToken, verifier);
		String uid = accessToken.getUid();
		AccountDomain account = UserService.ServiceHolder.getInstance()
				.getAccount(serviceType, uid);
		HttpSession session = request.getSession(true);
		UserDomain user = (UserDomain) session.getAttribute("user");
		if (account == null) {
			account = this.createAccount(serviceType, uid, user, accessToken);
		}
		try {
			serviceType.getStatusService().updateAccount(account);
		} catch (Exception e) {
			log.log(Level.SEVERE, e.getMessage(), e);
		}
		user.reloadAccount();
		request.getSession().setAttribute("user", user);
		return "redirect:/dashboard";
	}

	private AccountDomain createAccount(ServiceType serviceType, String uid,
			UserDomain user, YaYaAccessToken token) {
		AccountDomain account = new AccountDomain(serviceType, uid, user, token);
		account.setCreateAt(new Date());
		account.save();
		return account;
	}

	@Override
	public String getPath() {
		return "/callback";
	}

}
